//动态
<template>
	<div class="login-container">
	  <canvas id="canvas-bg"></canvas>
	  
	  <div class="login-form">
		<div class="form-tabs">
		  <button 
			:class="['tab-button', activeTab === 'login' ? 'active' : '']"
			@click="activeTab = 'login'"
		  >
			登录
		  </button>
		</div>
  
		<!-- 登录表单 -->
		<div v-show="activeTab === 'login'">
		  <h2 class="login-title">用户登录</h2>
		  <el-form 
			ref="loginFormRef" 
			:model="loginForm" 
			:rules="rules" 
			label-width="40px"
			class="demo-ruleForm" 
			status-icon
			
		  >
			<el-form-item label="邮箱" prop="u_email">
			  <el-input 
				v-model="loginForm.u_email"
				placeholder="请输入邮箱"
				prefix-icon="el-icon-message"
			  />
			</el-form-item>
  
			<el-form-item label="密码" prop="u_pwd">
			  <el-input 
				v-model="loginForm.u_pwd" 
				type="password" 
				placeholder="请输入密码"
				prefix-icon="el-icon-lock"
				show-password
			  />
			</el-form-item>
  
			<el-form-item>
			  <el-button 
				type="primary" 
				class="submit-button" 
				@click="submitForm(loginFormRef)"
				:loading="loading.login"
			  >
				登录
			  </el-button>
			</el-form-item>
		  </el-form>
		</div>
		<div class="form-footer">
					<span>还没有账号？</span>
					<a href="/register">立即注册</a>
				</div>
	  </div>
	</div>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import router from '@/router'
  import axios from 'axios';
  import register from "@/views/register.vue"; // 确保已安装 axios
  // 背景动画
  const initCanvasBg = () => {
	const canvas = document.getElementById('canvas-bg') as HTMLCanvasElement
	const ctx = canvas.getContext('2d')
	
	canvas.width = window.innerWidth
	canvas.height = window.innerHeight
	
	const particles: any[] = []
	const particleCount = 80
	const colors = ['rgba(100, 149, 237, 0.5)', 'rgba(138, 43, 226, 0.5)', 'rgba(75, 0, 130, 0.5)']
	
	// 创建粒子
	for (let i = 0; i < particleCount; i++) {
	  particles.push({
		x: Math.random() * canvas.width,
		y: Math.random() * canvas.height,
		size: Math.random() * 3 + 1,
		speedX: Math.random() * 2 - 1,
		speedY: Math.random() * 2 - 1,
		color: colors[Math.floor(Math.random() * colors.length)]
	  })
	}
	
	// 动画循环
	const animate = () => {
	  ctx.clearRect(0, 0, canvas.width, canvas.height)
	  
	  // 更新和绘制粒子
	  for (let i = 0; i < particles.length; i++) {
		const p = particles[i]
		
		p.x += p.speedX
		p.y += p.speedY
		
		// 边界检查
		if (p.x < 0 || p.x > canvas.width) p.speedX *= -1
		if (p.y < 0 || p.y > canvas.height) p.speedY *= -1
		
		// 绘制粒子
		ctx.beginPath()
		ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2)
		ctx.fillStyle = p.color
		ctx.fill()
		
		// 绘制连接线
		for (let j = i + 1; j < particles.length; j++) {
		  const p2 = particles[j]
		  const distance = Math.sqrt(Math.pow(p.x - p2.x, 2) + Math.pow(p.y - p2.y, 2))
		  
		  if (distance < 100) {
			ctx.beginPath()
			ctx.strokeStyle = `rgba(100, 149, 237, ${1 - distance / 100})`
			ctx.lineWidth = 0.5
			ctx.moveTo(p.x, p.y)
			ctx.lineTo(p2.x, p2.y)
			ctx.stroke()
		  }
		}
	  }
	  
	  requestAnimationFrame(animate)
	}
	
	animate()
	
	// 窗口大小调整
	window.addEventListener('resize', () => {
	  canvas.width = window.innerWidth
	  canvas.height = window.innerHeight
	})
  }
  
  onMounted(() => {
	initCanvasBg()
  })
  
  // 表单逻辑
  const activeTab = ref<'login' | 'register'>('login')
  const loading = reactive({
	login: false,
	register: false
  })
  
  // 登录表单
  interface LoginForm {
	u_email: string
	u_pwd: string
  }
  
  const loginFormRef = ref<FormInstance>()
  const loginForm = reactive<LoginForm>({
	u_email: '',
	u_pwd: ''
  })
  
  // 注册表单
  interface RegisterForm {
	username: string
	email: string
	password: string
	confirmPassword: string
  }
  
  const registerFormRef = ref<FormInstance>()
  const registerForm = reactive<RegisterForm>({
	username: '',
	email: '',
	password: '',
	confirmPassword: ''
  })
  
  // 验证规则
  const validateEmail = (rule: any, value: string, callback: any) => {
	const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
	if (!value) {
	  callback(new Error('请输入邮箱'))
	} else if (!emailRegex.test(value)) {
	  callback(new Error('请输入正确的邮箱格式'))
	} else {
	  callback()
	}
  }
  
  const validatePassword = (rule: any, value: string, callback: any) => {
	if (!value) {
	  callback(new Error('请输入密码'))
	} else if (value.length < 6) {
	  callback(new Error('密码长度不能少于6位'))
	} else {
	  callback()
	}
  }
  
  const validateConfirmPassword = (rule: any, value: string, callback: any) => {
	if (!value) {
	  callback(new Error('请再次输入密码'))
	} else if (value !== registerForm.password) {
	  callback(new Error('两次输入的密码不一致'))
	} else {
	  callback()
	}
  }
  
  const rules = reactive<FormRules<LoginForm>>({
	u_email: [{ validator: validateEmail, trigger: 'blur' }],
	u_pwd: [{ validator: validatePassword, trigger: 'blur' }]
  })
  
  const registerRules = reactive<FormRules<RegisterForm>>({
	username: [
	  { required: true, message: '请输入用户名', trigger: 'blur' },
	  { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
	],
	email: [{ validator: validateEmail, trigger: 'blur' }],
	password: [{ validator: validatePassword, trigger: 'blur' }],
	confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }]
  })
  
  // 提交登录表单
  const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  try {
    await formEl.validate();
    loading.login = true;
   // 发送登录请求
    const response = await axios.post('/api/login', {
      email: loginForm.u_email,
      password: loginForm.u_pwd
    });

    // 检查返回结果（假设后端返回 { success: true, token: 'xxx' }）
    if (response.data.success == 1) {
      // 存储 token（如 localStorage）
      localStorage.setItem('token', response.data.token);

      // 跳转到主页
      console.log("run")
      await router.push("/main");
      console.log("run")
    }
  } catch (error) {
    console.error("表单验证失败", error);
  } finally {
    loading.login = false;
  }
}
  
  // 提交注册表单
  const submitRegisterForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	
	try {
	  await formEl.validate()
	  loading.register = true
	  
	  const response = await register({
		username: registerForm.username,
		email: registerForm.email,
		password: registerForm.password
	  })
	  
	  console.log('注册成功', response.data)
	  activeTab.value = 'login'
	  registerFormRef.value?.resetFields()
	  
	  ElMessage.success('注册成功，请登录')
	} catch (error) {
	  console.error('注册失败', error)
	} finally {
	  loading.register = false
	}
  }
  </script>
  
  <style scoped lang="scss">
  .login-container {
	display: flex;
	justify-content: center;
	align-items: center;
	min-height: 100vh;
	position: relative;
	overflow: hidden;
	background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%);
	font-family: 'Helvetica Neue', Arial, sans-serif;
	
	#canvas-bg {
	  position: absolute;
	  top: 0;
	  left: 0;
	  width: 100%;
	  height: 100%;
	  z-index: 1;
	}
  }
  
  .login-form {
	position: relative;
	z-index: 2;
	background-color: rgba(15, 23, 42, 0.8);
	padding: 2.5rem 3rem;
	border-radius: 12px;
	box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
	width: 100%;
	max-width: 450px;
	backdrop-filter: blur(8px);
	border: 1px solid rgba(255, 255, 255, 0.1);
	transition: all 0.3s ease;
	
	&:hover {
	  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.4);
	}
  }
  
  .form-tabs {
	display: flex;
	justify-content: center;
	margin-bottom: 1.5rem;
	
	.tab-button {
	  background: none;
	  border: none;
	  color: rgba(255, 255, 255, 0.6);
	  font-size: 1.1rem;
	  padding: 0.5rem 1.5rem;
	  cursor: pointer;
	  position: relative;
	  transition: all 0.3s ease;
	  
	  &.active {
		color: #fff;
		font-weight: 500;
		
		&::after {
		  content: '';
		  position: absolute;
		  bottom: -5px;
		  left: 50%;
		  transform: translateX(-50%);
		  width: 60%;
		  height: 2px;
		  background: #6366f1;
		  border-radius: 2px;
		}
	  }
	  
	  &:hover {
		color: #fff;
	  }
	}
  }
  
  .login-title {
	text-align: center;
	color: #fff;
	font-size: 1.8rem;
	margin-bottom: 2rem;
	font-weight: 600;
  }
  
  :deep(.el-form) {
	.el-form-item__label {
	  color: rgba(255, 255, 255, 0.8);
	  padding-bottom: 0.5rem;
	}
	
	.el-input {
	  .el-input__wrapper {
		background-color: rgba(255, 255, 255, 0.05);
		border: 1px solid rgba(255, 255, 255, 0.1);
		box-shadow: none;
		transition: all 0.3s ease;
		
		&:hover {
		  border-color: rgba(255, 255, 255, 0.3);
		}
		
		&.is-focus {
		  border-color: #6366f1;
		  box-shadow: 0 0 0 1px #6366f1;
		}
	  }
	  
	  .el-input__inner {
		color: #fff;
		
		&::placeholder {
		  color: rgba(255, 255, 255, 0.4);
		}
	  }
	  
	  .el-input__prefix {
		color: rgba(255, 255, 255, 0.6);
	  }
	}
  }
  
  .submit-button {
	width: 100%;
	height: 46px;
	border-radius: 8px;
	font-size: 1rem;
	font-weight: 500;
	letter-spacing: 0.5px;
	margin-top: 1rem;
	background: linear-gradient(to right, #6366f1, #8b5cf6);
	border: none;
	transition: all 0.3s ease;
	
	&:hover {
	  background: linear-gradient(to right, #4f46e5, #7c3aed);
	  transform: translateY(-2px);
	}
	
	&:active {
	  transform: translateY(0);
	}
  }
  
  .form-footer {
	text-align: center;
	margin-top: 1.5rem;
	color: rgba(255, 255, 255, 0.6);
	font-size: 0.95rem;
	
	a {
	  color: #6366f1;
	  text-decoration: none;
	  margin-left: 0.5rem;
	  font-weight: 500;
	  cursor: pointer;
	  transition: all 0.2s ease;
	  
	  &:hover {
		text-decoration: underline;
	  }
	}
  }
  
  /* 响应式调整 */
  @media (max-width: 480px) {
	.login-form {
	  padding: 2rem 1.5rem;
	  margin: 0 1rem;
	}
	
	.login-title {
	  font-size: 1.5rem;
	}
  }
  </style>
